package com.example.concurrent.chapter07;

import java.util.concurrent.TimeUnit;

/**
 * @author Create By Liuqz
 * @date 2018/11/22 16:33
 */
public class ThreadHook {

    public static void main(String[] args) {
        //为应用程序注入钩子线程
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                System.out.println("The hook thread 1 is running");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("The hook thread 1 will exit");
        }));

        //钩子线程可以注册多个
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                System.out.println("The hook thread 2 is running");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("The hook thread 2 will exit");
        }));

        System.out.println("The program will is stopping");

        /**
         * result :
         * The program will is stopping
         * The hook thread 1 is running
         * The hook thread 2 is running
         * The hook thread 1 will exit
         * The hook thread 2 will exit
         *
         * 在main线程结束后,也就是JVM中没有了活动的非守护线程
         * JVM进行即将退出时,两个Hook线程将被启动并且运行
         */
    }
}
